<?php

namespace app\admin\service;

use app\admin\model\Category as CategoryModel;

class CategoryService
{
    protected $model;

    public function __construct(){
        $this->model = app()->make(CategoryModel::class);
    }

    /**
     * @return CategoryModel|CategoryModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryList()
    {
        $categoryList = $this->model->where('parent_id', 0)->order('sort desc,created_time asc')->select();
        foreach ($categoryList as $key=> $item) {
            $categoryList[$key]['childrenList'] = $this->model->where('parent_id', $item['id'])->select();
        }
        return $categoryList;
    }

    /**
     * @param array $idArr
     * @return CategoryModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryListByIdArr(array $idArr)
    {
        return $this->model->where('id', 'in' ,$idArr)->select();
    }

    /**
     * 查询分类详情
     *
     * @param int $id
     * @return CategoryModel|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryDetail(int $id){
        return $this->model->where('id', $id)->find();
    }
    public function save(array $data): bool
    {
        $result = null;
        if (empty($data['id'])) {
            $result = $this->model->insert($data);
        } else {
            $result = $this->model->where('id', $data['id'])->save($data);
        }
        return $result != null;
    }

    public function delete(int $id): bool
    {
        return $this->model->where('id', $id)->delete();
    }

    /**
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function queryCount(): int{
        return $this->model->count();
    }
}